package com.maixun.lib_choosefile.widget

import android.content.Context
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.tencent.smtt.sdk.TbsReaderView
import java.io.File

/**
 * @author：Lmoumou
 * @date：2020/10/20
 */
class SuperFileView: FrameLayout, TbsReaderView.ReaderCallback {
    constructor(context: Context) : this(context, null, 0)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        mTbsReaderView = TbsReaderView(context, this)
        this.addView(mTbsReaderView, LinearLayout.LayoutParams(-1, -1))
        mContext = context
    }

    private var mContext: Context
    private var mTbsReaderView: TbsReaderView
    var mOnGetFilePathListener: OnGetFilePathListener? = null

    fun displayFile(mFile: File) {
        if (!TextUtils.isEmpty(mFile.toString())) {
            val bsReaderTemp = "/storage/emulated/0/TbsReaderTemp"
            val bsReaderTempFile = File(bsReaderTemp)
            if (!bsReaderTempFile.exists()) {
                bsReaderTempFile.mkdir()
            }
            //加载文件
            val localBundle = Bundle()
            localBundle.putString("filePath", mFile.toString())
            localBundle.putString(
                "tempPath",
                Environment.getExternalStorageDirectory().toString() + "/" + "TbsReaderTemp"
            )
            val bool = mTbsReaderView.preOpen(getFileType(mFile.toString()), false)
            if (bool) {
                mTbsReaderView.openFile(localBundle)
            }
        }
    }

    private fun getFileType(paramString: String): String {
        var str = ""
        if (TextUtils.isEmpty(paramString)) {
            return str
        }
        val i = paramString.lastIndexOf('.')
        if (i <= -1) {
            return str
        }
        str = paramString.substring(i + 1)
        return str
    }

    fun show() {
        mOnGetFilePathListener?.onGetFilePath(this)
    }

    fun onStopDisplay() {
        mTbsReaderView.onStop()
    }

    interface OnGetFilePathListener {
        fun onGetFilePath(mSuperFileView: SuperFileView)
    }

    override fun onCallBackAction(p0: Int?, p1: Any?, p2: Any?) {

    }
}